package com.example.spring.boot.rabbitmq.configure;

import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfigure {


    @Autowired
    private RabbitProperties rabbitProperties;

    @Autowired
    private DemoConfirmCallBack demoConfirmCallBack;


    @Autowired
    private DemoReturnedCallback demoReturnedCallback;

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        return factory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //是生产者发布之后到达broker端的回调
        rabbitTemplate.setConfirmCallback(demoConfirmCallBack);

        //确保消息被consumer正确消费
        rabbitTemplate.setReturnsCallback(demoReturnedCallback);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setMessagePropertiesConverter(new DefaultMessagePropertiesConverter());
        return rabbitTemplate;
    }
}
